var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;// 导出的列
var params;// 查询参数
$(function() {
	
	// getList();
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});
	
	showArearList("area");
	
	var jspType = $("#jspType").val();
	if(jspType.startWith("kqiEvalution")){
		$("input[type='radio'][name=timeSize][value='"+$("#timeSize_link").val()+"']").attr("checked",true);
		if(jspType == 'kqiEvalution_sbsy' || jspType == 'kqiEvalution_sydksy'){
			$("#businessBigTypeId").val('1');//网页浏览
		}else if(jspType == 'kqiEvalution_spxzsl'){
			$("#businessBigTypeId").val('17');//视频下载
		}else if(jspType == 'kqiEvalution_imcgl'){
			$("#businessBigTypeId").val('18');//即时消息
		}
	}else if(jspType.startWith('kqi_evalution')){
		$("input[type='radio'][name=timeSize][value='"+$("#timeSize_link").val()+"']").attr("checked",true);
		var type = $("#type").val();
		if(type == 'sbsy' || type == 'sydksy'){
			$("#businessBigTypeId").val('1');//网页浏览
		}else if(type == 'spxzsl'){
			$("#businessBigTypeId").val('17');//P2P视频
		}else if(type == 'imcgl'){
			$("#businessBigTypeId").val('18');//即时消息
		}
		
		if(jspType == 'kqi_evalution_zczdphTable'){
			$("input[type='radio'][name=radio][value='2']").attr("checked",true);
			$("#terminalBrandId").val($("#terminal_brand").val());
			loadTerminalModel();
			getRadio();
		}else if(jspType == 'kqi_evalution_zcapnphTable'){
			//暂无APN信息
		}else if(jspType == 'kqi_evalution_zcxqTable'){
			$("input[type='radio'][name=radio][value='4']").attr("checked",true);
			$("#area").val($("#city_code").val());
			//$("#area option[value="+$("#city_code").val()+"]").attr("selected", true);
			getRadio();
		}else if(jspType == 'kqi_evalution_zcyhTable'){
			$("input[type='radio'][name=radio][value='1']").attr("checked",true);
			$("#userId").val($("#msisdn").val());
			getRadio();
		}
	}
	
	$("#businessBigTypeId").combobox({
		select : function(event, ui) {
			loadbusinessApp();
		}
	});
	$("#businessAppId").combobox();
	$("#terminalModelId").combobox();
	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select : function(event, ui) {
			loadTerminalModel();
		}
	});
	
	$("#sgw").combobox();
	
	
	if($("#jspType").val() == 'qwanalysis'){
		$("input[type='radio'][name=radio][value='4']").attr("checked",true);
		$("input[type='radio'][name=timeSize][value='day']").attr("checked",true);
		$("#eNodeBIDBox").attr("checked", true); 
		$("#eNodeBID").val($("#enodeb_id").val());
		$("#area").val($("#city_code").val());
		$("#area option[value="+$("#city_code").val()+"]").attr("selected", true);
		getRadio();
	}
})

/**
 * 根据业务大类，加载业务小类
 */
function loadbusinessApp() {
	var businessBigTypeId = $("#businessBigTypeId").val();

	$
			.ajax({
				url : '../../feature/appApply/appApplyInfos?appType='
						+ businessBigTypeId,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#businessAppId").remove();
					$("#businessAppTD")
							.append(
									$("<select id='businessAppId' name='businessAppId'></select>"));
					$("#businessAppId").combobox();
					var list = msg.appList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.app_type + "'>"
										+ item.app_name + "</option>")
								.appendTo($("#businessAppId"));
					});
				}
			});

}

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();

	$
			.ajax({
				url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
						+ terminalBrand,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#terminalModelId").remove();
					$("#terminalModelTD")
							.append(
									$("<select id='terminalModelId' name='terminalModelId'></select>"));
					
					$("#terminalModelId").append("<option value=''>全部</option>");
					var list = msg.terminalModelList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					});
					if($("#jspType").val() == 'kqi_evalution_zczdphTable'){
						$("#terminalModelId").val($("#terminal_model").val());
					}
					$("#terminalModelId").combobox();
				}
			});

}
/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 5; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 页面校验
 */
function validatorParam() {
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if (beginDate == null || beginDate == '') {
		alert("请选择开始时间");
		return false;
	}
	if (endDate == null || endDate == '') {
		alert("请选择结束时间");
		return false;
	}
	return true;
}
function getList() {
	delete d;
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	// 业务类型
	var businessBigTypeId = $("#businessBigTypeId").val();
	var businessBigTypeName=$("#businessBigTypeId").find("option:selected").text();
	var businessAppBox = $('input:checkbox[name="businessAppBox"]:checked')
			.val();
	var businessAppId = $("#businessAppId").val();
	var businessAppName=$("#businessAppId").find("option:selected").text();
	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();
	var groupId = $("#groupId").val();
	var userId = $("#userId").val();

	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();
	var sgw = $("#sgw").val();
	var cityCode = $("#area").val();
	var eNodeBID = $("#eNodeBID").val();
	var areaHouse = $("#areaHouse").val();
	if (validatorParam()) {
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined"
				|| datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		var columns = createColumns(businessAppBox, selectRadio);

		datatable = $('#table').dataTable({
			"bPaginate" : true, // 翻页功能
			"bLengthChange" : false, // 改变每页显示数据数量
			"bFilter" : false, // 过滤功能
			"bSort" : true, // 排序功能
			"bInfo" : true,// 页脚信息
			"bAutoWidth" : true,// 自动宽度
			// "sPaginationType": "full_numbers",//显示分页的样式
			// 还有simple_numbers等
//			"sScrollX" : "100%",
			"iDisplayLength" : 50,
			"sScrollXInner" : "110%",
			"bScrollCollapse" : true,
			"oLanguage" : {
				"sLengthMenu" : "每页显示 _MENU_条",
				"sZeroRecords" : "没有找到符合条件的数据",
				"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
				"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
				"sInfoEmpty" : "没有记录",
				"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
				"sSearch" : "搜索：",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "前一页",
					"sNext" : "后一页",
					"sLast" : "尾页"
				}
			},
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "../../businessAnalysis/hcq/getHcq",
			"fnServerData" : function(sSource, aoData, fnCallback) {
				// 清空一次参数，保证每次查询都是最新的
				delete params;
				var areaBoxStr = "";
				$("input[name='areaBox']:checkbox").each(function() {
					if ($(this).attr("checked")) {
						areaBoxStr += $(this).val() + "|";
					}
				});
				params = {
					"aoData" : JSON.stringify(aoData),
					"timeSize" : timeSize,
					"beginDate" : beginDate,
					"endDate" : endDate,
					"businessBigTypeId" : businessBigTypeId,
					"businessBigTypeName" : businessBigTypeName,
					"businessAppId" : businessAppId,
					"businessAppName" : businessAppName,
					"selectRadio" : selectRadio,
					"groupId" : groupId,
					"userId" : userId,
					"terminalBrandId" : terminalBrandId,
					"terminalModelId" : terminalModelId,
					"sgw" : sgw,
					"cityCode" : cityCode,
					"eNodeBID" : eNodeBID,
					"areaHouse" : areaHouse,
					"businessAppBox" : businessAppBox,
					"areaBoxStr" : areaBoxStr,
					"seriesName" : $("#seriesName").val(),
					"jspType"    : $("#jspType").val(),
					"type"       : $("#type").val()	
				};
				$.ajax({
					"type" : "POST",
					"contentType" : "application/x-www-form-urlencoded",
					"url" : sSource,
					"dataType" : "json",
					"data" : params, // 以json格式传递
					"success" : function(resp) {
						fnCallback(resp.pageDate);
						d = resp.allData;
					}
				});
			},
			columns : columns

		});
	}
}

/**
 * 构造页面显示的列
 * 
 * @param businessAppBox
 * @param selectRadio
 */
function createColumns(businessAppBox, selectRadio) {
	var columns = [];
	exportColumns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	// 时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "report_date",
		"name" : "时间",
		"value" : ""
	});
	// 业务大类
	trObj.append($("<th>业务大类</th>"));
	columns.push({
		data : "business_big_type_name",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "business_big_type_name",
		"name" : "业务大类",
		"value" : ""
	});
	// 根据页面条件显示
	// 显示服务IP
	if (businessAppBox == '0') {
		trObj.append($("<th >应用类型</th>"));
		columns.push({
			data : "business_app_name",
			render : function(data, type, row) {
				if (data == undefined) {
					return "";
				} else {
					return data;
				}
			}
		});
		exportColumns.push({
			"key" : "business_app_name",
			"name" : "应用类型",
			"value" : ""
		});
	}
	// SWG
	if (selectRadio == '3') {
		trObj.append($("<th >SGW</th>"));
		columns.push({
			data : "sgw_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "sgw_name",
			"name" : "SWG",
			"value" : ""
		});
	} else if (selectRadio == '4') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		columns.push({
			data : "city_code",
			render : function(data, type, row) {
				if (data == undefined) {
					return "";
				} else {
					return data;
				}
			}
		});
		exportColumns.push({
			"key" : "city_code",
			"name" : "地市",
			"value" : ""
		});
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox").each(function() {
			if ($(this).attr("checked")) {
				var areatBoxId = $(this).val();
				if (areatBoxId == '1') {// eNodeBID
					trObj.append($("<th >eNodeBID</th>"));
					columns.push({
						data : "enodeb_name",
						render : function(data, type, row) {
							if (data == undefined) {
								return "";
							} else {
								return data;
							}
						}
					});
					exportColumns.push({
						"key" : "enodeb_name",
						"name" : "eNodeBID",
						"value" : ""
					});
				} else if (areatBoxId == '2') {// 小区
					trObj.append($("<th >小区</th>"));
					columns.push({
						data : "cell_name",
						render : function(data, type, row) {
							if (data == undefined) {
								return "";
							} else {
								return data;
							}
						}
					});
					exportColumns.push({
						"key" : "cell_name",
						"name" : "小区",
						"value" : ""
					});
				}
			}
		});
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		var groupName = "";
		columns.push({
			data : "group_id",
			render : function(value, type, row) {
				$("#groupId option").each(function() {
					if ($(this).val() == value) {
						groupName = $(this).text();
					}
				});
				return groupName;
			}

		});
		// 后台需要处理
		exportColumns.push({
			"key" : "group_name",
			"name" : "用户组",
			"value" : $("#groupId").find("option:selected").text()
		});
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "user_msisdn",
			render : function(data, type, row) {
				if (data == undefined) {
					return "";
				} else {
					return data;
				}
			}
		});
		exportColumns.push({
			"key" : "user_msisdn",
			"name" : "MSISDN",
			"value" : ""
		});
		trObj.append($("<th >IMSI</th>"));
		columns.push({
			data : "imsi",
			render : function(data, type, row) {
				if (data == undefined) {
					return "";
				} else {
					return data;
				}
			}
		});
		exportColumns.push({
			"key" : "imsi",
			"name" : "IMSI",
			"value" : ""
		});
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
		var terminalBrandName = "";
		columns.push({
			data : "terminal_brand",
			render : function(value, type, row) {
				$("#terminalBrandId option").each(function() {
					if ($(this).val() == value) {
						terminalBrandName = $(this).text();
					}
				});
				return terminalBrandName;
			}
		});
		exportColumns.push({
			"key" : "terminal_brand",
			"name" : "终端类型",
			"value" : ""
		});

		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "user_terminal",
			render : function(value, type, row) {
				if(value==null){
					value = "";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "user_terminal",
			"name" : "终端型号",
			"value" : ""
		});
	}
	// 用户数
	trObj.append($("<th>用户数（个）</th>"));
	columns.push({
		data : "user_total",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "user_total",
		"name" : "用户数",
		"value" : ""
	});
	// 总流量
	trObj.append($("<th>总流量（MB）</th>"));
	columns.push({
		data : "flow_total",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "flow_total",
		"name" : "总流量",
		"value" : ""
	});
	// 上行包数
	trObj.append($("<th>上行包数（个）</th>"));
	columns.push({
		data : "up_pack_count",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "up_pack_count",
		"name" : "上行包数",
		"value" : ""
	});
	// 下行包数
	trObj.append($("<th>下行包数（个）</th>"));
	columns.push({
		data : "down_pack_count",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "down_pack_count",
		"name" : "下行包数",
		"value" : ""
	});
	// 上行流量
	trObj.append($("<th>上行流量（MB）</th>"));
	columns.push({
		data : "up_flow_count",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "up_flow_count",
		"name" : "上行流量",
		"value" : ""
	});
	// 下行流量
	trObj.append($("<th>下行流量（MB）</th>"));
	columns.push({
		data : "down_flow_count",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "down_flow_count",
		"name" : "下行流量",
		"value" : ""
	});
	// 下载速率
	trObj.append($("<th>下载速率</th>"));
	columns.push({
		data : "download_speed",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "download_speed",
		"name" : "下载速率",
		"value" : ""
	});
	// 首包时延
	trObj.append($("<th>首包时延(ms)</th>"));
	columns.push({
		data : "first_pack_time_delay",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "first_pack_time_delay",
		"name" : "首包时延",
		"value" : ""
	});
	// 首页时延
	trObj.append($("<th>首页时延(ms)</th>"));
	columns.push({
		data : "first_page_time_delay",
		render : function(data, type, row) {
			if (data == undefined) {
				return "";
			} else {
				return data;
			}
		}
	});
	exportColumns.push({
		"key" : "first_page_time_delay",
		"name" : "首页时延",
		"value" : ""
	});
	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

// function exportExcel() {
// if (d) {
// params['exportColumns'] = JSON.stringify(exportColumns);
// $
// .ajax({
// type : "POST",
// url : "../../businessAnalysis/hcq/exportBigDataExcel?rand="
// + Math.random(),
// dataType : "json",
// "data" : params,
// success : function(data) {
// if (data.flag) {
// var url = "../../businessAnalysis/hcq/downFiles?path="
// + data.path;
// window.location.href = url;
// } else {
// alert(data.msgs);
// }
// }
// });
// } else {
// alert("请先查询数据！");
// }
// }

// 下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}
/**
 * 显示树
 */
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
/**
 * 隐藏树
 */
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}

function exportExcel() {
	if (params == undefined || params == null || params == '') {
		alert("请先点击查询，然后导出！");
		return;
	}
	var countRecord = $("#table tbody tr :not(.dataTables_empty)").length;// 总行数
	if (countRecord == 0) {
		alert("没有可导出符合条件的的数据！");
		return;
	}
	params['exportColumns'] = JSON.stringify(exportColumns);
	$.ajax({
		type : "POST",
		url : "../../businessAnalysis/hcq/exportExcel?rand=" + Math.random(),
		dataType : "json",
		"data" : params,
		success : function(data) {
			if (data.flag) {
				var url = "../../businessAnalysis/hcq/downFiles?path="
						+ data.path;
				window.location.href = url;
			} else {
				alert(data.msgs);
			}
		}
	});
}
String.prototype.startWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substr(0, s.length) == s)
		return true;
	else
		return false;
	return true;
}